package com.gitee.ly.openfeign;

import feign.Client;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.cloud.openfeign.FeignContext;

import java.util.Map;

@Slf4j
public class LightRegistryFeignContext extends FeignContext {
    private final BeanFactory beanFactory;
    private final FeignContext delegate;

    public LightRegistryFeignContext(BeanFactory beanFactory, FeignContext bean) {
        this.beanFactory = beanFactory;
        this.delegate = bean;
    }

    @Override
    public <T> T getInstance(String name, Class<T> type) {
        T object = this.delegate.getInstance(name, type);
        if (type == Client.class) {
            return (T) this.wrapClient(object);
        } else {
            return object;
        }
    }

    @Override
    public <T> Map<String, T> getInstancesWithoutAncestors(String name, Class<T> type) {
        return this.delegate.getInstances(name, type);
    }

    Object wrapClient(Object bean) {
        try {
            Client defaultClient = bean == null ? new Client.Default(null, null) : (Client) bean;
            if (!(defaultClient instanceof LightRegistryFeignClient)) {
                return new LightRegistryFeignClient(defaultClient, this.beanFactory);
            } else {
                return defaultClient;
            }
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
        }
        return bean;
    }
}
